package com.scy.edu.client;

import com.scy.edu.common.JSONSerializer;
import com.scy.edu.common.RpcEncoder;
import com.scy.edu.handler.UserClientHandler;
import com.scy.edu.request.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 司晨雨
 * @date 2020/8/20 22:43
 * @description
 */
public class RpcConsumer {

    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler userClientHandler;

    //代理服务端ip
    private String ip;
    //代理服务端端口
    private int port;

    public RpcConsumer(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public static void initClient() throws InterruptedException {
        userClientHandler = new UserClientHandler();

        NioEventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,true).handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                pipeline.addLast(new StringDecoder());
                pipeline.addLast(userClientHandler);
            }
        });
        bootstrap.connect("127.0.0.1",8888).sync();
    }

    public static Object createProxy(Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(userClientHandler == null){
                    initClient();
                }

                RpcRequest request = new RpcRequest();
                request.setMethodName(method.getName());
                request.setClassName(method.getDeclaringClass().getName());
                request.setParameters(args);
                request.setParameterTypes(method.getParameterTypes());

                userClientHandler.setParam(request);

                Object result = executor.submit(userClientHandler).get();

                return result;
            }
        });
    }


}
